package org.hh.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.hh.netty.entity.Message;
import org.hh.netty.entity.User;

import java.util.List;

/**
 * 教师端服务
 */
public class TeacherServer implements Runnable{

    public void run() {
        TeacherServerHandler teacherServerHandler = new TeacherServerHandler();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        //nio模式的线程池，workerGroup负责处理数据
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        //创建服务端启动类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .channel(NioServerSocketChannel.class)      //指定IO模型
                .group(bossGroup, workerGroup)              //线程模型
                .childHandler(new ChannelInitializer<NioSocketChannel>() {      //连接读写处理
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new ObjectEncoder());
                        pipeline.addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                        pipeline.addLast(teacherServerHandler);
                    }
                }).bind(8888);

        //显示启动消息
        TeacherModel teacherModel = TeacherModel.getInstance();
        teacherModel.addMessage(User.getSystemUser(), new Message(1, "服务已启动，端口8888"));

        //显示用户列表
        teacherModel.getUserObservableList().add(User.getSystemUser());

    }
}
